package com.wsj.servlet;

import com.wsj.filter.MyFilter;
import com.wsj.servlet.MyServlet;
import java.util.EnumSet;
import java.util.Set;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * description:自定义添加servlet,filter
 * @author yang
 * @date 2019/8/6 11:36
 */
public class CustomServletContainerInitializer implements ServletContainerInitializer {

  private final static String JAR_HELLO_URL = "/hello";

  @Override
  public void onStartup(Set<Class<?>> c, ServletContext servletContext) throws ServletException {
    System.out.println("创建 helloWorldServlet...");

    ServletRegistration.Dynamic servlet = servletContext.addServlet(MyServlet.class.getSimpleName(), MyServlet.class);
    servlet.addMapping(JAR_HELLO_URL);

    System.out.println("创建 helloWorldFilter...");

    FilterRegistration.Dynamic filter = servletContext.addFilter(MyFilter.class.getSimpleName(), MyFilter.class);

    EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class);
    dispatcherTypes.add(DispatcherType.REQUEST);
    dispatcherTypes.add(DispatcherType.FORWARD);

    filter.addMappingForUrlPatterns(dispatcherTypes, true, JAR_HELLO_URL);
  }
}
